package com.my.ads.lib;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.NativeExpressAdView;
import com.my.ads.lib.bean.AdxBannerAd;
import com.my.ads.lib.bean.AdxNativeAd;
import com.my.ads.lib.bean.BeanList;
import com.my.ads.lib.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import static com.my.ads.lib.Config.ADX_ID_INTER_E;
import static com.my.ads.lib.Config.ADX_ID_NATIVE_E;

/**
 * Created by xuanyang on 2018/3/2.
 */

public class AdxUtils {


    public List<AdxBannerAd> adxBannerAds = new ArrayList<>();
    public List<AdxBannerAd> adxBannerAdsEcmp = new ArrayList<>();
    int bannerSize = 5;

    private NativeExpressAdView adView;


    private static AdxUtils instance = new AdxUtils();

    public static AdxUtils getInstance() {
        return instance;
    }


    public void cacheAdxInterstitialAd(Context context) {
        if (BeanList.mEcpmInterList.size() <= 4) {
            requestInterstitialAd(context, ADX_ID_INTER_E);
        }
    }

    private void requestInterstitialAd(final Context context, final String ADX_ID_INTER_E) {
        Log.i(Config.TagLog, "adx i begin");
        final com.google.android.gms.ads.InterstitialAd mInterstitialAd = new com.google.android.gms.ads.InterstitialAd(context);
        mInterstitialAd.setAdUnitId(ADX_ID_INTER_E);
        mInterstitialAd.loadAd(new AdRequest.Builder().build());
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(int i) {
                Log.i(Config.TagLog, "adx i error : " + i);
            }

            @Override
            public void onAdLoaded() {
//                if (mInterstitialAd.isLoaded()) { // 这个判断有必要吗？
                    Log.i(Config.TagLog, "adx i success");
                    addInterstitialAd(mInterstitialAd);
//                }
            }
        });
    }

    private void addInterstitialAd(com.google.android.gms.ads.InterstitialAd mInterstitialAd) {
        BeanList.mEcpmInterList.add(0, mInterstitialAd);
    }


    /////////////////
    public void cacheAdxNativeAd(Context context) {
        if (BeanList.mEcpmNativeList.size() <= 10) {
            Log.i(Config.TagLog, "adx begin");
            requestNativeAd(context, ADX_ID_NATIVE_E);
        }
    }

    private void requestNativeAd(final Context context, final String ADX_ID_NATIVE_E) {
        final NativeExpressAdView adView = new NativeExpressAdView(context);
        Utils.loadNewNative(context, adView, ADX_ID_NATIVE_E, new AdListener() {

            @Override
            public void onAdFailedToLoad(int i) {
                Log.i(Config.TagLog, "adx n error : " + i);
            }

            @Override
            public void onAdLoaded() {
                Log.i(Config.TagLog, "adx n success");
                addNativeAd(adView);
            }
        });
    }

    private void addNativeAd(NativeExpressAdView adView) {

        try {
            AdxNativeAd adxNativeAd = new AdxNativeAd();
            adxNativeAd.setNativeAd(adView);
            adxNativeAd.setHasShowed(false);
            adxNativeAd.setAdTime(System.currentTimeMillis());
            BeanList.mEcpmNativeList.add(0, adxNativeAd);
            BeanList.mEcpmNativeList = Utils.removeAdByTimeoutAndAlreadyShowadx(BeanList.mEcpmNativeList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //////////////////
    public void cacheAdxBannerAd(final Context context) {
        if (adxBannerAdsEcmp.size() <= bannerSize) {
            Log.i(Config.TagLog, "adx b begin");
            final AdView adView = new AdView(context);
            adView.setAdSize(AdSize.BANNER);
            adView.setAdUnitId(Config.ADX_ID_BANNER1);
            adView.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    Log.i(Config.TagLog, "adx b success");
                    AdxBannerAd localAdxBannerAd = new AdxBannerAd();
                    localAdxBannerAd.setNativeAd(adView);
                    localAdxBannerAd.setHasShowed(false);
                    localAdxBannerAd.setAdTime(System.currentTimeMillis());
                    adxBannerAdsEcmp.add(0, localAdxBannerAd);
                    adxBannerAdsEcmp = AdUtils.removeBannerAdByTimeout(adxBannerAdsEcmp);
                    adxBannerAdsEcmp = AdUtils.removeBannerAdByShow(adxBannerAdsEcmp);
                }
            });
            adView.loadAd(new AdRequest.Builder().build());

            if (adxBannerAds.size() <= bannerSize) {
                final AdView other = new AdView(context);
                other.setAdSize(AdSize.BANNER);
                other.setAdUnitId(Config.ADX_ID_BANNER2);
                other.setAdListener(new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        AdxBannerAd localAdxBannerAd = new AdxBannerAd();
                        localAdxBannerAd.setNativeAd(other);
                        localAdxBannerAd.setHasShowed(false);
                        localAdxBannerAd.setAdTime(System.currentTimeMillis());
                        adxBannerAds.add(0, localAdxBannerAd);
                        adxBannerAds = AdUtils.removeBannerAdByTimeout(adxBannerAds);
                        adxBannerAds = AdUtils.removeBannerAdByShow(adxBannerAds);
                    }
                });
                other.loadAd(new AdRequest.Builder().build());
            }
        }
    }


    ////////////////////
    public void showAdxInterstitial(final Context context, int activityType, final String PageName, int priority) {

        if (priority == 0) {
            if (BeanList.mEcpmInterList != null && !BeanList.mEcpmInterList.isEmpty()) {
                final com.google.android.gms.ads.InterstitialAd interstitialAd = BeanList.mEcpmInterList.get(0);
                BeanList.mEcpmInterList.remove(0);

                if (interstitialAd != null) {
                    interstitialAd.show();
                    interstitialAd.setAdListener(new AdListener() {
                        @Override
                        public void onAdClosed() {
                            super.onAdClosed();
                            if (!TextUtils.isEmpty(PageName)) { // 启动应用自身的主界面
                                AdUtils.startTargetActivity(context, PageName);
                            }
                        }
                    });
                    //ControlCenter.recordInterShowTime(context);
                    SharedPreferences sp = context.getSharedPreferences(Config.InterstitialAdTarget, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();

                    editor.putLong(Config.InterstitialAdTimeShow, System.currentTimeMillis());
                    editor.apply();
                }
            } else {
                showAdxInterstitial(context, activityType, PageName, priority + 1);
            }
        } else if (priority == 1) {
            if (BeanList.mLowInterList != null && !BeanList.mLowInterList.isEmpty()) {
                final com.google.android.gms.ads.InterstitialAd interstitialAd = BeanList.mLowInterList.get(0);
                BeanList.mLowInterList.remove(0);

                if (interstitialAd != null) {
                    interstitialAd.show();
                    interstitialAd.setAdListener(new AdListener() {
                        @Override
                        public void onAdClosed() {
                            super.onAdClosed();
                            if (!TextUtils.isEmpty(PageName)) {
                                AdUtils.startTargetActivity(context, PageName);
                            }
                        }
                    });
                    SharedPreferences sp = context.getSharedPreferences(Config.InterstitialAdTarget, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();

                    editor.putLong(Config.InterstitialAdTimeShow, System.currentTimeMillis());
                    editor.apply();
                }
            }
        }
    }



    /////////////////////////////
    public void showAdxNativeAd(final Context context, final RelativeLayout parent, final int position, final boolean isFromLockScreen, final int priority) {

        if (parent == null) {
            return;
        }
        if (parent.getChildCount() != 0) {
            parent.removeAllViews();
        }
        adxNativeShow(context, parent, position, isFromLockScreen, priority);
    }

    public void adxNativeShow(final Context context, final RelativeLayout parent, final int position, final boolean isLockScreenAd, final int priority) {
        Log.i(Config.TagLog, "adx n begin");
        if (priority == 0) {
            if (BeanList.mEcpmNativeList != null && !BeanList.mEcpmNativeList.isEmpty() && BeanList.mEcpmNativeList.get(0) != null) {
                makeAdxNativeAd(context, parent, BeanList.mEcpmNativeList);
            } else {
                adxNativeShow(context, parent, position, isLockScreenAd, 1);
            }
        } else if (priority == 1) {
            if (BeanList.mLowNativeList != null && !BeanList.mLowNativeList.isEmpty() && BeanList.mLowNativeList.get(0) != null) {
                if(isLockScreenAd){
                    if (!AdUtils.isShowLockScreenAd()){
                        return;
                    }
                }
                makeAdxNativeAd(context, parent, BeanList.mLowNativeList);
            }
        }
    }

    private void makeAdxNativeAd(final Context context, final RelativeLayout parent, List<AdxNativeAd> adxNativeAdList) {

        Log.i(Config.TagLog, "adx n show");
        parent.setVisibility(View.VISIBLE);
        adView = adxNativeAdList.get(0).getNativeAd();
        ViewGroup viewGroup = (ViewGroup) adView.getParent();
        if (viewGroup != null) {
            viewGroup.removeAllViews();
        }
        Utils.addCenterInParentToAdView(adView);
        parent.addView(adView);
        BeanList.mEcpmNativeList.remove(0);
        AdUtils.recordNativeShowTime(context);
    }



    ///////////////////////
    public void showAdxBanner(final RelativeLayout parent) {

        if (parent == null) {
            return;
        }

        Log.i(Config.TagLog, "adx b show");

        parent.setVisibility(View.GONE);

        if (adxBannerAdsEcmp != null && adxBannerAdsEcmp.size() > 0) {
            parent.setVisibility(View.VISIBLE);
            ViewGroup viewGroup = (ViewGroup) adxBannerAdsEcmp.get(0).getNativeAd().getParent();
            if (viewGroup != null) {
                viewGroup.removeAllViews();
            }

            parent.removeAllViews();
            parent.setGravity(Gravity.CENTER);
            parent.addView(adxBannerAdsEcmp.get(0).getNativeAd());

            adxBannerAdsEcmp.get(0).setHasShowed(true);
            adxBannerAdsEcmp.remove(0);

        } else if (adxBannerAds != null && adxBannerAds.size() > 0) {
            parent.setVisibility(View.VISIBLE);
            ViewGroup viewGroup = (ViewGroup) adxBannerAds.get(0).getNativeAd().getParent();
            if (viewGroup != null) {
                viewGroup.removeAllViews();
            }

            parent.removeAllViews();
            parent.setGravity(Gravity.CENTER);
            parent.addView(adxBannerAds.get(0).getNativeAd());

            adxBannerAds.get(0).setHasShowed(true);
            adxBannerAds.remove(0);

        }
    }


}
